import { concat, fromEvent } from "rxjs";
import { buffer, bufferCount, bufferTime, debounce, debounceTime, filter, map, switchMap, takeUntil, throttleTime } from "rxjs/operators";
import { getLogger } from "../utils";

const log0 = getLogger("Purpose");
log0("demonstate mouse down and drag events, you can erase the color in the canvas");

const canvas = document.createElement("canvas");
canvas.style.cursor = "pointer";
const SIDE = 400;
canvas.width = SIDE;
canvas.height = SIDE;
const ctx = canvas.getContext("2d")
ctx.beginPath();
ctx.rect(0, 0, SIDE, SIDE);
ctx.fillStyle = "lightblue";
ctx.fill();

document.body.appendChild(canvas);

const mouseDown$ = fromEvent<MouseEvent>(document, "mousedown");
const mouseMove$ = fromEvent<MouseEvent>(document, "mousemove");
const mouseUp$ = fromEvent<MouseEvent>(document, "mouseup");

const mouseDrag$ = mouseDown$.pipe(switchMap(() => {
    return mouseMove$.pipe(
        takeUntil(mouseUp$),
        throttleTime(10, null, { leading: true, trailing: true }),
    );
}),
    filter(e => e.target === canvas),
    map(e => ({ x: e.offsetX, y: e.offsetY })),
    bufferCount(2),
);

mouseDrag$.subscribe(([e1, e2]) => {
    // console.log(`${e1.x}, ${e1.y} -> ${e2.x}, ${e2.y}`);
    ctx.beginPath();
    ctx.lineWidth = 4;
    ctx.strokeStyle = "magenta";
    ctx.moveTo(e1.x, e1.y);
    ctx.lineTo(e2.x, e2.y);
    ctx.stroke();
});
